package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/9/20
 * Time: 13:29
 */
public class Utils {
    public static WebDriver driver;
    public static String DrawUrl = "http://101.42.27.228:8080/draw.html?activityName=%E6%B5%8B%E8%AF%95&activityId=28&valid=true";

    public Utils(String url) {
        // 调用driver对象
        driver = createDriver();
        driver.get(url);
    }

    /**
     * 创建驱动对象
     * @return
     */
    public static WebDriver createDriver() {
        if (driver == null) {
            // 下载驱动
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            // 允许访问所有的链接
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            // 隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    /**
     * 屏幕截图
     */
    public static void screenShot(String func) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTile = sim2.format(System.currentTimeMillis());

        String filename = "./src/test/java/images/" + dirTime + "/" + func + "_" + fileTile + ".png";

        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, new File(filename));
    }

    /**
     * 切换子页面
     * @param xpath
     */
    public static void locationSubpage(String xpath) {
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));

        driver.switchTo().defaultContent();
        driver.findElement(By.xpath(xpath)).click();
        // 确保在frame中
        driver.switchTo().frame("contentFrame");
    }
}
